package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.R;
import com.atguigu.commonutils.RandomUtil;
import com.atguigu.msmservice.service.MsmService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msmapi")
@CrossOrigin
@Api(description = "获取手机验证码")
public class MsmApiController {

    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("send/{phone}")
    @ApiOperation(value = "获取手机验证码")
    public R code(@PathVariable String phone){
        //先从Redis中获取验证码，如果回去到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) return R.ok();

        //生成随机的值
        code = RandomUtil.getFourBitRandom();

        Map<String,Object> param = new HashMap<>();
        param.put("code", code);
        Boolean isSend = msmService.send(param, phone);
        if(isSend){
            //如果发送成功，把发送成功的验证码放入redis中，并设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else{
            return R.error().message("短信发送失败！！");
        }
    }

    @GetMapping("setValue/{phone}")
    @ApiOperation(value = "模拟发送手机验证码")
    public R setValue(@PathVariable String phone){
        String code = RandomUtil.getFourBitRandom();
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        return R.ok().data("code",code);
    }

    @GetMapping("getValue/{phone}")
    @ApiOperation(value = "测试获取手机验证码")
    public R getValue(@PathVariable String phone){
        String s = redisTemplate.opsForValue().get(phone);
        return R.ok().data("code",s);
    }
}
